package com.laowang.project.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.*;
import com.laowang.common.utils.ip.IpUtils;
import com.laowang.framework.redis.RedisCache;
import com.laowang.project.pay.config.MyWxPayConfigUtil2;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.PayObject;
import com.laowang.project.system.domain.vo.RankVo;
import com.laowang.project.system.service.ZcWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.laowang.project.system.mapper.ZcWxOrderMapper;
import com.laowang.project.system.service.ZcWxOrderService;

import javax.servlet.http.HttpServletRequest;

/**
 * order对象Service业务层处理
 *
 * @author laowang
 * @date 2025-09-09
 */
@Service
public class ZcWxOrderServiceImpl implements ZcWxOrderService {
    @Autowired
    private ZcWxOrderMapper zcWxOrderMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ZcWxOrderService zcWxOrderService;
    @Autowired
    private ZcWxUserService zcWxUserService;

    /**
     * 查询order对象
     *
     * @param id order对象ID
     * @return order对象
     */
    @Override
    public ZcWxOrder selectZcWxOrderById(String id) {
        return zcWxOrderMapper.selectZcWxOrderById(id);
    }

    /**
     * 查询order对象列表
     *
     * @param zcWxOrder order对象
     * @return order对象
     */
    @Override
    public List<ZcWxOrder> selectZcWxOrderList(ZcWxOrder zcWxOrder) {
        return zcWxOrderMapper.selectZcWxOrderList(zcWxOrder);
    }

    /**
     * 新增order对象
     *
     * @param zcWxOrder order对象
     * @return 结果
     */
    @Override
    public int insertZcWxOrder(ZcWxOrder zcWxOrder) {
        zcWxOrder.setCreateTime(DateUtils.getNowDate());
        return zcWxOrderMapper.insertZcWxOrder(zcWxOrder);
    }

    /**
     * 修改order对象
     *
     * @param zcWxOrder order对象
     * @return 结果
     */
    @Override
    public int updateZcWxOrder(ZcWxOrder zcWxOrder) {
        return zcWxOrderMapper.updateZcWxOrder(zcWxOrder);
    }

    /**
     * 批量删除order对象
     *
     * @param ids 需要删除的order对象ID
     * @return 结果
     */
    @Override
    public int deleteZcWxOrderByIds(String[] ids) {
        return zcWxOrderMapper.deleteZcWxOrderByIds(ids);
    }

    /**
     * 删除order对象信息
     *
     * @param id order对象ID
     * @return 结果
     */
    @Override
    public int deleteZcWxOrderById(String id) {
        return zcWxOrderMapper.deleteZcWxOrderById(id);
    }

    @Override
    public List<RankVo> selectZcWxOrderRankList(Integer type) {
        return zcWxOrderMapper.selectZcWxOrderRankList(type);
    }

    @Override
    public Map<String, Object> payOrder(ZcWxOrder zcWxOrder, HttpServletRequest request) {


        //支付的用户
        ZcWxUser zcWxUser = SecurityUtils.getLoginUser().getZcWxUser();
        //元
        BigDecimal totalPrice = zcWxOrder.getTotalPrice();

        if (Objects.isNull(totalPrice)) {
            throw new CustomException("总价不能为空", 400);
        }


        ZcWxOrder wxOrder1 = new ZcWxOrder();


        String ipAddr = IpUtils.getIpAddr(request);
        MyWxPayConfigUtil2 myWxPayConfigUtil = new MyWxPayConfigUtil2();
        //myWxPayConfigUtil.setAppId(WxConfig.APP_ID);
        myWxPayConfigUtil.setTxamt(String.valueOf(totalPrice.multiply(new BigDecimal(100)).intValue()));
        String orderId = String.valueOf(idWorker.nextId());
        Date date = new Date();
        myWxPayConfigUtil.setOrderNo("zc" + orderId);
        myWxPayConfigUtil.setOpenid(zcWxUser.getOpenid());
        myWxPayConfigUtil.setDate(date);
        myWxPayConfigUtil.setIp(ipAddr);
        try {

            wxOrder1.setTotalPrice(totalPrice);
            wxOrder1.setCreateTime(date);
            Integer shareId = zcWxOrder.getShareId();
            //有分享人的情况就是捐款发起者 才是主题，被分享者付款是支持者
            if (shareId != null) {
                ZcWxUser zcWxUser1 = zcWxUserService.selectZcWxUserById(shareId);
                if (zcWxUser1 != null) {
                    wxOrder1.setUserId(shareId);
                    wxOrder1.setSupporter(zcWxUser.getId());


                }else {
                    wxOrder1.setUserId(zcWxUser.getId());
                }

            }else {
                wxOrder1.setUserId(zcWxUser.getId());
            }

            wxOrder1.setTotalPrice(totalPrice);
            wxOrder1.setActivityId(zcWxOrder.getActivityId());
            //0待支付,1已支付,2已退款,3关闭支付,4已删除"
            wxOrder1.setStatus(0);
            wxOrder1.setCreateTime(date);
            wxOrder1.setId("zc" + orderId);
            wxOrder1.setExpireTime(DateUtil.adjustDateByHour(date, 1, 1));
            wxOrder1.setType(zcWxOrder.getType());
            wxOrder1.setRemark(zcWxOrder.getRemark());
            // 公众号支付
            Map<String, Object> map = PayUtil2.test8(myWxPayConfigUtil);
            if (map.get("code").equals("000000")) {
                String s = JSONObject.toJSONString(map.get("data"));

                Map<String, String> map1 = JSONObject.parseObject(s, Map.class);
                System.out.println("map1:" + map1);
                //map1:{agetId=6100518974, getPrepayId=1, jsapiAppid=wxc53e21e72bf9cba9,
                // orderNo=20241101TTT8mesa, orderTime=20241101112543, threeOrderNo=1852190256204349440,
                // jsapiPaySign=C5577/Fmtn9Lwk/sOAVzwLv/a6NQAs9DmO6AtoskK0Nv98RS4eKneCJMg6egoyGAvygrWlWrXsN+MRXkneI6Xb2mGvr2hn4qs9g2Aox+oL7ZjrFLj8mVGGGXDZ2mcUgzMIFfcXa1QwLGD47rWZ/c8rJT2LIFbe7RAykMnX77MnZXQih1eBFI7aaofPB1LMK7+IqjBeyU7VqrBf0Pv7SJnnX9MEPQw5s+GwlgvA/DOFz/Qqw0q2b1UZMEIfcHbpMENLbAuzUTP4xwLcinTBUFRJD03L+w+ghklevlGtPu3QA4tOPlGM6GLp7MNUTTK7h9QzEauCQ2XHjypUBleer3kg==,
                // prePayId=wx01112543528106078f6b6be55a1df70000,
                // jsapiSignType=RSA, jsapiNoncestr=204ccccb3bab47d38cb22c4c8d27463c, jsapiTimestamp=1730431543,
                // jsapiPackage=prepay_id=wx01112543528106078f6b6be55a1df70000}

                wxOrder1.setPrepayId(map1.get("prePayId"));// 预支付id
                wxOrder1.setOrderNo(map1.get("orderNo"));// 国通交易订单号

                //wxOrder.setPayStr(s);
                zcWxOrderMapper.insertZcWxOrder(wxOrder1);
                // 监听订单过期 修改订单状态
                redisCache.setCacheObject("zc:" + "zc"+orderId, "abc", 30, TimeUnit.MINUTES);
            } else {
                throw new CustomException((String) map.get("msg"), 400);
            }
            map.put("zcOrderId", "zc" + orderId);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new CustomException("支付异常", 400);

    }
}
